package net.maxwoods.nimble.spring.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private static final Logger loggger=LoggerFactory.getLogger(CustomAuthenticationProvider.class);

    @Autowired
    private Environment environment;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        Authentication a=SecurityContextHolder.getContext().getAuthentication();
        String b=environment.getProperty("b");
        CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails) authentication.getDetails();  // 如上面的介绍，这里通过authentication.getDetails()获取详细信息
        loggger.info("remote address:{}",details.getRemoteAddress());
        loggger.info("session id:{}",details.getSessionId());
        loggger.info("code:{}",details.getCode());
        loggger.info("authentication:{}",authentication);
        // 下面是验证逻辑，验证通过则返回UsernamePasswordAuthenticationToken，
        // 否则，可直接抛出错误（AuthenticationException的子类，在登录验证不通过重定向至登录页时可通过session.SPRING_SECURITY_LAST_EXCEPTION.message获取具体错误提示信息）
        if (true) {
            // 添加权限
            ArrayList<CustomeGrantedAuthority> authorities=new ArrayList<>();
            authorities.add(new CustomeGrantedAuthority("ROLE_ADMIN"));
            authorities.add(new CustomeGrantedAuthority("ROLE_DBA"));
            //
            CustomUserDetails userDetails=new CustomUserDetails(1L,"a","b",true,authorities);
            UsernamePasswordAuthenticationToken token1=new UsernamePasswordAuthenticationToken(details,authentication.getCredentials(),userDetails.getAuthorities());
            CustomAuthenticationToken token2=new CustomAuthenticationToken(details,authentication.getCredentials(),authorities);
            token2.setDetails(userDetails);
            token2.setAuthenticated(true);
            return token2;
        } else {
            throw new UsernameNotFoundException("你要显示的错误信息");
        }
    }


    @Override
    public boolean supports(Class<?> authentication) {
        loggger.info("==========认证类型判断:{}",authentication);
        //return authentication.equals(UsernamePasswordAuthenticationToken.class);
        return true;
    }
}